<?php

namespace App\Console\Commands;

use App\Library\Logic\WithdrawLogic;
use App\Library\MySeasLog;
use App\Library\YsdLib;
use Exception;
use Illuminate\Console\Command;
use Yansongda\Pay\Pay;

class WithdrawQueryCommand extends Command
{
    /**
     * 查询提现信息
     *
     * @var string
     */
    protected $signature = 'command:withdrawQuery {serialNumber}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * handle
     * @return void
     * @throws Exception
     */
    public function handle(): void
    {
        $serialNumber = $this->argument('serialNumber');
        if (empty($serialNumber) || strlen($serialNumber) !== 20) return;
        $withdraw = WithdrawLogic::findBySerialNumber($serialNumber);
        if (is_null($withdraw)) return;
        else if ($withdraw->status_arrival !== 99) return;
        try {
            $query = Pay::wechat(YsdLib::config())->query([
                'out_batch_no' => $serialNumber,
                'out_detail_no' => $serialNumber,
                '_action' => 'transfer',
            ]);
            if ($query->detail_status === 'SUCCESS') {
                $withdraw->pay_at = $query->initiate_time;
                $withdraw->status_arrival = 1;
            } else if($query->detail_status === 'FAIL') {
                $withdraw->status_arrival = 2;
                $withdraw->remark = $query->fail_reason;
            }
            $withdraw->find = $query;
            $withdraw->save();
        } catch (Exception $e) {
            MySeasLog::critical([$e->getCode(), $e->getMessage()]);
            $k = 'withdrawQuery:' . $serialNumber;
            if (!cache()->has($k)) {
                mq('withdrawQuery', $serialNumber, 30);
                cache()->increment($k);
            } else if (cache($k) === 3) cache()->forget($k);
        }
    }
}
